package service

import (
	"cap_client/global"
	"encoding/json"
	"fmt"
	"lib/cmdutil"
	"lib/structs/cap"
	"lib/utils"
	"time"
)

var ClientSer = new(clientService)

type clientService struct {
}

func (s clientService) Register() (err error) {
	// 1. 执行插件，获取注册信息
	// 2. 发送注册请求
	var bs []byte
	bs, err = s.execCli([]string{"mccp", "info", "-sayHi="}, "/client/register")
	if err != nil {
		return err
	}
	global.ClientId = utils.StrToInt64(string(bs))
	return nil
}

func (s clientService) UploadCloudApp() (err error) {
	option := cmdutil.CommandOption{
		TimeoutDuration: time.Duration(3) * time.Second,
		Env:             fmt.Sprintf("%s/plugin/", global.Conf.AppFolder),
	}
	stdout, stderr, err := cmdutil.RunCommandArgs([]string{"mccp", "info", fmt.Sprintf("-apps=%s", "C:\\miao\\app")}, option)
	if err != nil {
		err = fmt.Errorf("插件调用时发生错误,err:[%v],stdout:[%s],stderr:[%s]", err, stdout, stderr)
		return
	}
	var apps []cap.AppInfo
	err = json.Unmarshal([]byte(stdout), &apps)
	if err != nil {
		return err
	}
	if len(apps) == 0 {
		apps = make([]cap.AppInfo, 0)
	}
	in := struct {
		AppList []cap.AppInfo `json:"appList"`
		HostId  int64         `json:"hostId,string"`
	}{}
	in.AppList = apps
	in.HostId = global.ClientId
	var bs []byte
	bs, err = json.Marshal(in)
	if err != nil {
		return err
	}
	_, err = utils.HttpClient.Post(fmt.Sprintf("%s%s", global.Conf.CapServ, "/client/uploadCloudApp"), bs, nil)
	return err
}

func (s clientService) CreateRdpWinAccount(kvs []string) (err error) {
	_, err = s.execCli([]string{"mccp", "user", fmt.Sprintf("-add=%s", utils.ArrStringToStr(kvs))}, "/client/uploadCloudApp")
	return err
}

func (s clientService) NoticeWinSessionChange(in cap.WinSessionChangeMsg) (err error) {
	data := struct {
		Msg    cap.WinSessionChangeMsg `json:"msg"`
		HostId int64                   `json:"hostId,string"`
	}{
		Msg:    in,
		HostId: global.ClientId,
	}

	bs, err := json.Marshal(data)
	if err != nil {
		return
	}
	bs, err = utils.HttpClient.Post(fmt.Sprintf("%s/%s", global.Conf.CapServ, "client/winSessionChange"), bs, nil)
	return
}

func (s clientService) execCli(argus []string, uri string) (bs []byte, err error) {
	option := cmdutil.CommandOption{
		TimeoutDuration: time.Duration(3) * time.Second,
		Env:             fmt.Sprintf("%s/plugin/", global.Conf.AppFolder),
	}
	stdout, stderr, err := cmdutil.RunCommandArgs(argus, option)
	if err != nil {
		err = fmt.Errorf("插件调用时发生错误,err:[%v],stdout:[%s],stderr:[%s]", err, stdout, stderr)
		return
	}
	regInfo := cap.RegisterInfo{
		Uid:         global.Conf.AppHost.Uid,
		Ip:          global.Conf.AppHost.Ip,
		GuaPort:     global.Conf.AppHost.GuaPort,
		Api:         global.Conf.AppHost.Api,
		Status:      1,
		GuaProtocol: "cap",
		Description: stdout,
	}
	bs, _ = json.Marshal(regInfo)
	bs, err = utils.HttpClient.Post(fmt.Sprintf("%s%s", global.Conf.CapServ, uri), bs, nil)
	return
}
